<?php
namespace App\Http\Controllers\Common;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
class UploadsController extends Controller
{
    protected $accessKey;
    protected $secretKey;
    protected $bucket;
    protected $domainUrl;
    public function __construct()
    {
        $this->accessKey = env('QINIU_ACCESS_KEY');
        $this->secretKey = env('QINIU_SECRET_KEY');
        $this->bucket    = env('QINIU_BUCKET_NAME');
        $this->domainUrl = env('QINIU_DOMAIN_URL');
    }

    /**
     * 获取七牛云配置
     * @return array
     */
    public function qiNiuConfig()
    {
        $arr = [
            'accessKey' => $this->accessKey,
            'secretKey' => $this->secretKey,
            'bucket' => $this->bucket,
            'domainUrl' => $this->domainUrl,
        ];
        return $arr;
    }

    /**
     * 后台上传图片功能
     * @param Request $request
     * @return void
     */
    public function image(Request $request)
    {
        $maxSize = 10;
        $allowed_extensions = ['png', 'jpg', 'gif', 'jpeg','webp','svga'];
        $data = ['code' => self::RESPONSE_CODE_ERROR, 'msg' => '上传失败'];
        //获取图片格式
        $extensionType = $request->get('extensionType');
        $allowed_extensions = empty($extensionType) ?  $allowed_extensions : [$extensionType];

        $file = $request->file('file');
        //获取桶名称
        $type = $request->get('type');
        //上传大小限制-M
        $postMaxSize = $request->get('postMaxSize','');
        if ($postMaxSize) {
            $maxSize=$postMaxSize;
        }

        if (!$file) {
            $data = ['code' => self::RESPONSE_CODE_ERROR, 'msg' => '上传失败'];
            return response()->json($data);
        }
        if ($file->isValid()) {
            $ext = $file->getClientOriginalExtension();
            if (!in_array(strtolower($ext), $allowed_extensions)) {
                $data['msg'] = '请上传' . implode(',', $allowed_extensions) . '格式的图片';
                return response()->json($data);
            }

            if ($file->getSize() > $maxSize * 1024 * 1024) {
                $data['msg'] = '图片大小限制' . $maxSize . 'M';
                return response()->json($data);
            }
        } else {
            $data['msg'] = $file->getErrorMessage();
            return response()->json($data);
        }
        //图片上传
        // 获取文件相关信息
        $filePath = $file->getPathname();
        //新的文件名称
        $newFileName = date('His') . rand(1000, 99999) . '.' . $ext;
        //新的目录名称
        $mkdirName = "images/".date("ymd");
        //是否上传七牛
        $isUploadQiNiu = config::get("images.isUploadQiNiu");
        if(!$isUploadQiNiu){
            $url = $file->storeAs($mkdirName, $newFileName, 'uploads');
            if (!$url) {
                $data = ['code' => self::RESPONSE_CODE_ERROR, 'msg' => '上传失败'];
                return $data;
            }
            $imageUrl = "/uploads/" . $url;
        }else{
            $fileName = "uploads/".$mkdirName."/".$newFileName;
            //Log::info("图片上传七牛 filePath:" . $filePath.",filename:" . $fileName);
            $this->imageTuQiniu($filePath,$fileName);
            //获取七牛配置
            $qiNiuConfig = $this->qiniuConfig();
            $domainUrl = $qiNiuConfig['domainUrl'];
            $imageUrl = $domainUrl."/".$fileName;
        }
        $data = [
            'code' => self::RESPONSE_CODE_SUCCESS,
            'msg' => '上传成功',
            'url' => $imageUrl
        ];
        return response()->json($data);

    }


    /**
     * 图片上传七牛
     * @param $filePath //文件的绝对位置 C:\Users\Administrator\AppData\Local\Temp\php43E2.tmp
     * @param $fileName //文件名称 uploads/ueditor/250905/14062880783.jpeg
     * @return void
     */
    public function imageTuQiniu($filePath,$fileName)
    {
        // 获取七牛云配置
        $qiNiuConfig = $this->qiNiuConfig();
        $accessKey = $qiNiuConfig['accessKey'];
        $secretKey = $qiNiuConfig['secretKey'];
        $bucket = $qiNiuConfig['bucket'];
        // 初始化鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 生成上传策略
        $policy = null;
        $uptoken = $auth->uploadToken($bucket, null, 3600, $policy);
        // 初始化 UploadManager 对象并进行文件上传
        $uploadMgr = new UploadManager();
        list($ret, $err) = $uploadMgr->putFile($uptoken,$fileName,$filePath);
        if ($err !== null) {
            // 返回上传失败的信息
            Log::error("图片上传七牛-fail");
            return false;
        } else {
            Log::info("图片上传七牛-success: key: ".$ret['key'].",hash:".$ret['hash']);
            return true;
        }
    }

    /**
     * 获取所有的七牛云图片入库
     * @return void
     */
    public function listFiles()
    {
        //获取七牛云配置
        $qiNiuConfig = $this->qiNiuConfig();
        $accessKey = $qiNiuConfig['accessKey'];
        $secretKey = $qiNiuConfig['secretKey'];
        $bucket = $qiNiuConfig['bucket'];
        // 初始化鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        $bucketManager = new BucketManager($auth);
        $options = 'soft_article/'; // 默认参数，可以不传任何参数获取所有文件列表
        list($ret, $err) = $bucketManager->listFiles($bucket, $options);
        if ($err !== null) {
            return ['error' => $err];
        } else {
            $newPic=[];
            $i = 0;
            foreach ($ret['items'] as $key=>$val) {
                if($val['fsize'] > 0){
                    $newPic[$i]['keyword']=" ";
                    $newPic[$i]['thumbs']= "https://qinipic.pindarpr.com/".$val['key'];
                    $newPic[$i]['created_at'] = date("Y-m-d H:i:s");
                    $newPic[$i]['updated_at'] = date("Y-m-d H:i:s");
                    $i++;
                }
            }
            if($newPic){
                 $newPicArr = array_chunk($newPic,1000);
                 foreach ($newPicArr as $k=>$v){
                     DB::table("pd_ai_images")->insert($v);
                 }
            }
            echo "success:".date("Y-m-d H:i:s")."\n";
            exit();
        }
    }


}
